use crate::http_api::message::SatoriMessageData;
use crate::model::satori::{SatoriGuild, SatoriMessage, SatoriUser};
use crate::ws::{AppState, SenderData};
use uuid::Uuid;
use void_log::log_info;

/// # Websocket消息通道
impl AppState {
    pub async fn message_create(&self, message_data: SatoriMessageData, from_user: &str) {
        // 判断来源Channel
        let channel = message_data.channel_id;
        log_info!("发送至: {}", &channel);

        // 判断是否私聊
        let from_username = if channel.starts_with("private:") {
            // 私聊加private
            format!("private:{}", from_user)
        } else {
            // 群聊来源本群
            channel.clone()
        };
        log_info!("消息来源: {}", &from_username);

        // 组装发送方User
        let satori_user = if let Ok(satori_user) = SatoriUser::select_username(&self.pool, from_user).await {
            log_info!("用户 {} 查询成功", from_user);
            satori_user
        } else {
            log_info!("用户 {} 不存在", from_user);
            return;
        };

        // 组装发送方来源
        let satori_guild = if let Ok(guild_id) = Uuid::parse_str(&from_username) {
            log_info!("群组 {} 查询成功", &from_username);
            SatoriGuild::select(&self.pool, &guild_id).await.unwrap_or(SatoriGuild::new(&from_username))
        } else {
            log_info!("群组 {} 不存在", &from_username);
            SatoriGuild::new(&from_username)
        };

        // 组装Message
        let satori_message = SatoriMessage {
            id: Uuid::new_v4().to_string(),
            content: message_data.content.unwrap(),
            guild: Some(satori_guild),
            user: Some(satori_user),
            ..Default::default()
        };

        // 标记接收方
        let sender_data = SenderData {
            to_user: channel.to_string(),
            satori_message,
        };
        self.sender_tx.send(sender_data).await.unwrap();
    }
}